/*
 * @Author       : wfl
 * @LastEditors: wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-10 10:36:53
 * @LastEditTime: 2023-04-14 10:09:19
 */
import { ikStore } from 'iking-utils'

let btns: Array<string> | null = null
let btnList: Array<{
  [x: string]: string
  permissionCode: string
}> = []

/**
 * @description: 按钮权限 用法： v-role="'按钮permissionCode值'"
 * @description: 如果要使用系统返回的按钮名称，则在code值前添加$符，如：v-role="'$ADD-USER'"
 * @return {*}
*/
const BtnRole = {
  name: 'role',
  mounted: (el: HTMLElement, binding: { value: string; }) => {
    const code = binding.value
    if (!code)
      return true
    if (!el)
      return false
    const _code = binding.value.startsWith('$') ? binding.value.substring(1) : binding.value
    btnList = ikStore.session.getItem(MenuStorageEnum.BUTTON)
    btns = btnList?.map((b: any) => b?.permissionCode)
    const menuList = ikStore.session.getItem(MenuStorageEnum.MENU).map((v: any) => v.permissionCode)
    // code存在且不在权限时
    if (!btns?.includes(_code) && !menuList?.includes(_code)) {
      el?.remove()
    }
    else {
      const btn = btnList?.find(b => b.permissionCode === _code)
      if (typeof code === 'string' && code.startsWith('$') && btn)
        el.innerHTML = `<span>${btn?.name}</span>`
    }
  }
}

export default BtnRole
